package com.app.studyroom.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.app.studyroom.R;
import com.app.studyroom.api.model.message.AnnouncementItem;
import com.app.studyroom.mapper.AnnouncementTypeMapper;

import java.util.List;

public class AnnouncementAdapter extends RecyclerView.Adapter<AnnouncementAdapter.ViewHolder> {

    public interface OnDeleteListener {
        void onDelete(AnnouncementItem item);
    }

    private Context context;
    private List<AnnouncementItem> data;
    private OnDeleteListener deleteListener;

    public AnnouncementAdapter(Context context, List<AnnouncementItem> data, OnDeleteListener deleteListener) {
        this.context = context;
        this.data = data;
        this.deleteListener = deleteListener;
    }

    public void updateData(List<AnnouncementItem> newData) {
        this.data = newData;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public AnnouncementAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_announcement_manage, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull AnnouncementAdapter.ViewHolder holder, int position) {
        AnnouncementItem item = data.get(position);

        holder.tvType.setText(AnnouncementTypeMapper.toChinese(item.getMessageType()));
        holder.tvContent.setText(item.getMessage());

        holder.btnDelete.setOnClickListener(v -> {
            if (deleteListener != null) {
                deleteListener.onDelete(item);
            }
        });
    }

    @Override
    public int getItemCount() {
        return data != null ? data.size() : 0;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvTime, tvType, tvContent;
        Button btnDelete;

        ViewHolder(View itemView) {
            super(itemView);
            tvType = itemView.findViewById(R.id.tvType);
            tvContent = itemView.findViewById(R.id.tvContent);
            btnDelete = itemView.findViewById(R.id.btnDelete);
        }
    }
}
